//
//  DetailReplyInputView.swift
//  MM2
//
//  Created by 李成明 on 2022/1/11.
//

import UIKit

class DetailReplyInputView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(note:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHiden(note:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    var replyModel: DailyReplyModel? {
        didSet {
            replyModel == nil ? (placeHolder.text = "说点什么吧～") : (placeHolder.text = "h回复\(replyModel!.userName)")
        }
    }
    
    var replyCompleteClosure: ((DailyReplyModel) -> Void)?
    var forumId = 0
    
    private var isInputWord = false {
        didSet {
            placeHolder.isHidden = isInputWord
            
            postBtn.isUserInteractionEnabled = isInputWord
            postBtn.isHighlighted = isInputWord
            postBtn.layer.borderColor = isInputWord ? UIColor.initWithRGB(97, 167, 247).cgColor : mainColor.cgColor
        }
    }
    
    private var textViewHeight: CGFloat = 35 {
        willSet {
            viewHeight = viewHeight - textViewHeight + newValue
            textView.frame.size.height = newValue
            self.frame.origin.y = kScreenHeight - viewHeight
        }
    }
    private let textViewWidth = kScreenWidth - 188
    private(set) var viewHeight: CGFloat = 35 + kTabBarAndSafeH
    
    private lazy var bgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "daily_detail_input_bg"))
        return view
    }()
    
    private lazy var downIcon: UIImageView = {
        let view = UIImageView(image: UIImage(named: "daily_detail_input_down_icon"))
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(downIconClickAction))
        view.addGestureRecognizer(tap)
        view.isUserInteractionEnabled = true
        return view
    }()
    
    private lazy var textView: UITextView = {
        let view = UITextView()
        view.delegate = self
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 10
        view.layer.borderColor = mainColor.cgColor
        view.layer.borderWidth = 1
        view.font = .systemFont(ofSize: 16)
        return view
    }()
    
    private lazy var placeHolder: UILabel = {
        let view = UILabel()
        view.font = .systemFont(ofSize: 16)
        view.textColor = mainColor
        view.text = "说点什么吧～"
        return view
    }()
    
    private lazy var postBtn: UIButton = {
        let view = UIButton()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 8
        view.layer.borderWidth = 1
        view.layer.borderColor = mainColor.cgColor
        view.titleLabel?.font = .systemFont(ofSize: 16)
        view.setTitleColor(mainColor, for: .normal)
        view.setTitleColor(.initWithRGB(97, 167, 247), for: .highlighted)
        view.setTitle("发送", for: .normal)
        view.isHighlighted = false
        view.addTarget(self, action: #selector(postClickAction), for: .touchUpInside)
        view.isUserInteractionEnabled = false
        return view
    }()
}

extension DetailReplyInputView {
    private func setupUI() {
        backgroundColor = .white
        self.addsubViews([bgView, textView, postBtn, downIcon])
        textView.addsubViews([placeHolder])
        placeHolder.frame = CGRect(x: 8, y: 10, width: 100, height: 20)
        textView.frame = CGRect(x: 16, y: 7, width: textViewWidth, height: textViewHeight)
        
        postBtn.snp.makeConstraints { make in
            make.right.equalTo(self).offset(-56)
            make.centerY.equalTo(textView.snp.centerY)
            make.size.equalTo(CGSize(width: 80, height: 30))
        }
        
        downIcon.snp.makeConstraints { make in
            make.right.equalTo(self).offset(-10)
            make.centerY.equalTo(textView.snp.centerY)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        bgView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
    }
}

extension DetailReplyInputView: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        isInputWord = !textView.text.isEmpty
        
        if textView.text.count >= 200 {
            guard let str = textView.text else { return }
            let index = str.index(str.startIndex, offsetBy: 199)
            textView.text = String(str[str.startIndex...index])
        }
        
        let size = textView.sizeThatFits(CGSize(width: textViewWidth, height: CGFloat.greatestFiniteMagnitude))
        if size.height != textViewHeight {
            textViewHeight = size.height
        }
    }
}

extension DetailReplyInputView {
    
    func showUp() {
        self.textView.becomeFirstResponder()
    }
    
    @objc private func keyBoardWillShow(note: Notification) {
        guard let userInfo = note.userInfo else {return}
        guard let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else{return}
        //获取动画执行的时间
        let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double ?? 0.25
        
        //获取键盘弹起的高度
        let keyboardTopYPosition = keyboardRect.height
        
        UIView.animate(withDuration: duration, delay: 0, options: .allowAnimatedContent, animations: {
            self.viewHeight = (keyboardTopYPosition + self.textViewHeight + 14)
            self.frame = CGRect(x: 0, y: kScreenHeight - self.viewHeight, width: kScreenWidth, height: self.viewHeight)
        }, completion: nil)
    }
    
    @objc private func keyBoardWillHiden(note: Notification) {
        guard let userInfo = note.userInfo else {return}
        //获取动画执行的时间
        let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double ?? 0.25

        UIView.animate(withDuration: duration, delay: 0, options: .allowAnimatedContent, animations: {
            self.viewHeight = kSafeAreaBottomH + 14 + self.textViewHeight
            self.frame = CGRect(x: 0, y: kScreenHeight - self.viewHeight, width: kScreenWidth, height: self.viewHeight)
        }, completion: nil)
    }
    
    @objc private func postClickAction() {
        MoyaNetwork.request(target: BaseApi.commont(dailyId: forumId, content: textView.text ?? "", toReplyId: replyModel?.userId ?? 0)) { _, _ in
            let newReplyModel = DailyReplyModel()
            newReplyModel.forumId = self.forumId
            newReplyModel.userId = User.share.userId
            newReplyModel.userName = User.share.userName
            newReplyModel.touserId = self.replyModel?.userId ?? 0
            newReplyModel.touserName = self.replyModel?.userName ?? ""
            newReplyModel.content = self.textView.text ?? ""
            
            self.textView.resignFirstResponder()
            self.textView.text = ""
            self.isInputWord = false
            self.replyCompleteClosure?(newReplyModel)
        }
    }
    
    @objc private func downIconClickAction() {
        textView.resignFirstResponder()
        replyModel = nil
    }
    
    @discardableResult
    func commontClick(_ closure: @escaping ((DailyReplyModel) -> Void)) -> DetailReplyInputView {
        replyCompleteClosure = closure
        return self
    }
}
